package com.sduept.nwld.dataserver.controller.assessment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.fault.special.maintenance.manager.MaintenanceManager;
//import com.sduept.cim.model.extend.special.maintenance.MaintenanceStation;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStation;
import com.sduept.bigdata.special.maintenance.model.MaintenanceStationBreaker;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.services.ManagementUnitService;


/**
 * 特维分析
 *
 */

	@Named
	@ViewScoped
    public class SpecialMaintenanceAnalysisController extends AbstractController{

	/**
	 *
	 */
	private static final long serialVersionUID = -1712731668218936007L;

	private List<SpFinishedDetail4Vol> finishedList4Vol=new ArrayList<SpFinishedDetail4Vol>();

	private List<MaintenanceStation> spStations;//所有特维站
	private List<ManagementUnitDict> mechanismEntitys;//所有调管范围
	private Date currentDate;//当前日期
	private int selectedYear;

	private static final int[] vols={500,220};

	private MaintenanceStation queryMS = new MaintenanceStation();
	private String cutPowerPlanQuery = null; //是否安排了停电计划
	private String finishBeforeQuery = null; //是否6.30之前应该完成
	private String finishQuery = null; //6.30之前是否已经完成
	private Date finishedTimeStart; //完成时间
	private Date finishedTimeEnd; //完成时间

	private UnfinishedDetail4TransMechanism selectedItem;//选择的某个电压等级下的某个调管范围

	private List<MaintenanceBlanksInfo> blankInfos=new ArrayList<>();//某个站下的特维信息（右边特维信息）

	private TreeNode root;
	private TreeNode selectedNode;//选择的站节点

	@Autowired
	private MaintenanceManager mm;
	@Autowired
	private ManagementUnitService unitM;

	@PostConstruct
	private void init() {
		Calendar calendar=Calendar.getInstance();
		selectedYear=calendar.get(Calendar.YEAR);
		currentDate=calendar.getTime();
		try {
			mechanismEntitys = unitM.getAllDispatchingManagements();
		} catch (ManagementUnitException e) {
		}
		queryMS.setYear(selectedYear);
		query();
	}

	public void changeYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		String year = map.get("yearAnalysis").toString();
		selectedYear = Integer.valueOf(year);
		queryMS.setYear(selectedYear);
	}

	public void query() {
		finishedList4Vol.clear();
		spStations = mm.getMaintenanceStationByCondition(queryMS, cutPowerPlanQuery, finishBeforeQuery, finishQuery, null, null, finishedTimeStart, finishedTimeEnd);
		if(spStations.size()>0){
			for(int i=0;i<vols.length;i++){
				getUnfinishedList(vols[i]);
			}
		}
	}

	public void resetQuery() {
		queryMS = new MaintenanceStation();
		Calendar calendar = Calendar.getInstance();
		selectedYear = calendar.get(Calendar.YEAR);
		queryMS.setYear(selectedYear);
		cutPowerPlanQuery = null;
		finishBeforeQuery = null;
		finishQuery = null;
		finishedTimeStart = null;
		finishedTimeEnd = null;
		query();
	}

	/**
	 * 根据选择的调管范围，电压等级和年份得到特维间隔和特维断路器信息
	 */
	public void getMaintenanceInfo(UnfinishedDetail4TransMechanism item) {
		blankInfos.clear();
		selectedItem=item;
		genTree();
	}
	//点击站，展示特维信息
	public void onNodeSelect(NodeSelectEvent event) {
		blankInfos.clear();
		String stationName=event.getTreeNode().getData().toString();
		//组织{pid:[MaintenanceStationBreaker]}
		//2020-05-20 应该是间隔id，对应的断路器，不应该是站对应的,由于ID可能是空，使用name
		Map<String,List<MaintenanceStationBreaker>> breakersMap = new HashMap<>();//{pid:[breakers]}
		List<MaintenanceStationBreaker> allBreakers=mm.getBreakersByYear(selectedItem.getYear());//所有的特维断路器
		for (MaintenanceStationBreaker b : allBreakers) {
			List<MaintenanceStationBreaker> breakers=breakersMap.get(b.getBayName());
			if(null==breakers) {
				breakers=new ArrayList<>();
			}
			breakers.add(b);
			breakersMap.put(b.getBayName(), breakers);
		}

		List<MaintenanceStation> blanks=new ArrayList<>();
		blanks.addAll(selectedItem.getUnfinishedBlanks());
		blanks.addAll(selectedItem.getFinishedBlanks());

		for(MaintenanceStation blank:blanks) {
			if(stationName.equals(blank.getStation())) {
				List<MaintenanceStationBreaker> breakers=breakersMap.get(blank.getBlankName());
				MaintenanceBlanksInfo blankInfo=new MaintenanceBlanksInfo(blank, breakers);
				blankInfos.add(blankInfo);
			}
		}
		Collections.sort(blankInfos, new Comparator<MaintenanceBlanksInfo>() {
			@Override
			public int compare(MaintenanceBlanksInfo o1, MaintenanceBlanksInfo o2) {
				if(!o1.blank.isFinish()&&o2.blank.isFinish()) {
					return -1;
				}else if(o1.blank.isFinish()&&o2.blank.isFinish()) {
					return 0;
				}
				return 1;
			}

		});

	}


	//产生左侧树节点
	private void genTree() {
		Set<String> finshedStations=new HashSet<>();
		Set<String> unfinshedStations=new HashSet<>();
		//未完成的站
		for(MaintenanceStation blank:selectedItem.getUnfinishedBlanks()) {
			unfinshedStations.add(blank.getStation());
		}
		//已完成的站
		for(MaintenanceStation blank:selectedItem.getFinishedBlanks()) {
			if(!unfinshedStations.contains(blank.getStation())) {
				finshedStations.add(blank.getStation());
			}
		}
		root = new DefaultTreeNode("Root", null);
		for(String station:unfinshedStations) {
			new DefaultTreeNode("unfinishedRoot", station, root);
		}
		for(String station:finshedStations) {
			new DefaultTreeNode("finishedRoot", station, root);
		}
	}

	private void getUnfinishedList(int vol){
		List<UnfinishedDetail4TransMechanism> unfinishedList=new ArrayList<UnfinishedDetail4TransMechanism>();
		mechanismEntitys = sortMechanismEntitys(mechanismEntitys);
		for(ManagementUnitDict m:mechanismEntitys){
			UnfinishedDetail4TransMechanism u=new UnfinishedDetail4TransMechanism();
			u.setTransMechanism(m.getName());
			u.setVoltage(vol);
			u.setYear(selectedYear);
			if("总调".equals(m.getName())){
				u.setTransMechanism("南网总调");
			}
			unfinishedList.add(u);
		}
		SpFinishedDetail4Vol finishDetail=new SpFinishedDetail4Vol(vol);//完成情况总计
		Set<String> spStaionId=new HashSet<>();//特维厂站
		Set<String> unfinishedSpStaionId=new HashSet<>();//未完成的站
		outer:for (MaintenanceStation maintenanceStation : spStations) {
			if(vol==maintenanceStation.getVoltage()&&maintenanceStation.getTransMechanism()!=null ){
				spStaionId.add(maintenanceStation.getStation());
				for (UnfinishedDetail4TransMechanism d : unfinishedList) {
					if(maintenanceStation.getTransMechanism().equals(d.getTransMechanism()) || (maintenanceStation.getTransMechanism().contains("总调")&&d.getTransMechanism().contains("总调")) ){
						setUnfinishedDetail4TransMechanismNum(maintenanceStation,d,unfinishedSpStaionId);
						continue outer;
					}
				}
				UnfinishedDetail4TransMechanism detail=new UnfinishedDetail4TransMechanism();
				detail.setTransMechanism(maintenanceStation.getTransMechanism());
				setUnfinishedDetail4TransMechanismNum(maintenanceStation,detail,unfinishedSpStaionId);
				unfinishedList.add(detail);
			}
		}
		finishDetail.setUnfishedList(unfinishedList);//未完成基本情况
		finishDetail.setSpStations(spStaionId);
		finishDetail.setUnfinishedStations(unfinishedSpStaionId);//未完成特维站
		getSpFinishedDetail4Vol(unfinishedList,finishDetail,vol);
	}

	/**
	 * 得到总体完成情况
	 * @param unfishedList
	 * @param vol
	 */
	private void getSpFinishedDetail4Vol(List<UnfinishedDetail4TransMechanism> unfishedList,SpFinishedDetail4Vol finishDetail,int vol){
		UnfinishedDetail4TransMechanism total=finishDetail.getTotalDetail();
		total.setVoltage(vol);
		total.setYear(selectedYear);
		for(UnfinishedDetail4TransMechanism d : unfishedList){
			float finishRate=1;
			if((d.getUnfinishedBlanks().size()+d.getFinishedBlanks().size())!=0){
				finishRate=((float)d.getFinishedBlanks().size())/(d.getFinishedBlanks().size()+d.getUnfinishedBlanks().size());
				d.setFinishRate(finishRate);
			}else {
				finishRate = 1;
				d.setFinishRate(finishRate);
			}

			//计算合计
			total.getFinishedBlanks().addAll(d.getFinishedBlanks());//已完成间隔
			total.getOverPlanBlanks().addAll(d.getOverPlanBlanks());//未到计划停电日期
			total.getUnReachedPlanBlanks().addAll(d.getUnReachedPlanBlanks());//已超计划停电日期
			total.getUnfinishedBlanks().addAll((d.getUnfinishedBlanks()));//未完成
		}
		finishDetail.getSpBlanks().addAll(total.getFinishedBlanks());//合计特维间隔总数
		finishDetail.getSpBlanks().addAll(total.getUnfinishedBlanks());//合计特维间隔总数

		float rate=1;
		if(finishDetail.getSpBlanks().size()!=0){
			rate = ((float)total.getFinishedBlanks().size())/finishDetail.getSpBlanks().size();
			total.setFinishRate(rate);
		}else {
			rate = 1;
			total.setFinishRate(rate);
		}

		total.setTransMechanism("合计");
		if(unfishedList.size()>0){
			unfishedList.add(total);
		}
		finishedList4Vol.add(finishDetail);
	}

	//计算数值
	private void setUnfinishedDetail4TransMechanismNum(MaintenanceStation m,UnfinishedDetail4TransMechanism d,Set<String> unfinishedSpStaionId){
		if(m.isFinish()){
			d.getFinishedBlanks().add(m);
		}else{
			//没有停电计划的都是未到计划时间？？？
			if(m.getChuandongTime()!=null && m.getChuandongTime().before(currentDate)) {
				d.getOverPlanBlanks().add(m);
			}else{
				d.getUnReachedPlanBlanks().add(m);
			}
			d.getUnfinishedBlanks().add(m);
			unfinishedSpStaionId.add(m.getStation());
		}
	}

	/**
	 * 调管范围按照南网总调、广东中调、广西中调、云南中调、贵州中调、海南中调、广州中调、深圳中调排序
	 * @param mechanismEntitys
	 * @return
	 */
	private List<ManagementUnitDict> sortMechanismEntitys(List<ManagementUnitDict> mechanismEntitys){
		List<ManagementUnitDict> sortMechanismEntitys = new ArrayList<>();
		List<String> names = MechanismEntityNames();
		for(String name:names) {
			for(ManagementUnitDict unit:mechanismEntitys) {
				if(unit.getName().contains(name)) {
					sortMechanismEntitys.add(unit);
				}
			}
		}
		//		for(ManagementUnitDict l: sortMechanismEntitys) {
		//			log.info(l.getName());
		//		}
		return sortMechanismEntitys;
	}

	/**
	 * 调管范围按照南网总调、广东中调、广西中调、云南中调、贵州中调、海南中调、广州中调、深圳中调排序
	 * @return
	 */
	private List<String> MechanismEntityNames(){
		List<String> names = new ArrayList<>();
		//调管范围按照南网总调、广东中调、广西中调、云南中调、贵州中调、海南中调、广州中调、深圳中调排序
		names.add("南网");
		names.add("广东");
		names.add("广西");
		names.add("云南");
		names.add("贵州");
		names.add("海南");
		names.add("广州");
		names.add("深圳");
		return names;
	}


	/**
	 * 某电压等级下的特维完成情况
	 *
	 */
	public class SpFinishedDetail4Vol{
		private int voltage;
		private Set<String> spStations=new HashSet<>();//特维站id
		private Set<String> unfinishedStations=new HashSet<>();//未完成的厂站
		private List<MaintenanceStation> spBlanks=new ArrayList<>();//间隔
		private UnfinishedDetail4TransMechanism totalDetail=new UnfinishedDetail4TransMechanism();//合计
		private List<UnfinishedDetail4TransMechanism> unfishedList=new ArrayList<>();
		public SpFinishedDetail4Vol(int vol){
			this.voltage=vol;
		}

		public int getVoltage() {
			return voltage;
		}
		public void setVoltage(int voltage) {
			this.voltage = voltage;
		}
		public List<UnfinishedDetail4TransMechanism> getUnfishedList() {
			return unfishedList;
		}
		public void setUnfishedList(List<UnfinishedDetail4TransMechanism> unfishedList) {
			this.unfishedList = unfishedList;
		}

		public UnfinishedDetail4TransMechanism getTotalDetail() {
			return totalDetail;
		}

		public void setTotalDetail(UnfinishedDetail4TransMechanism totalDetail) {
			this.totalDetail = totalDetail;
		}

		public Set<String> getSpStations() {
			return spStations;
		}

		public void setSpStations(Set<String> spStations) {
			this.spStations = spStations;
		}

		public Set<String> getUnfinishedStations() {
			return unfinishedStations;
		}

		public void setUnfinishedStations(Set<String> unfinishedStations) {
			this.unfinishedStations = unfinishedStations;
		}

		public List<MaintenanceStation> getSpBlanks() {
			return spBlanks;
		}

		public void setSpBlanks(List<MaintenanceStation> spBlanks) {
			this.spBlanks = spBlanks;
		}


	}

	/**
	 * 按照调管范围分组的特维未完成情况
	 *
	 */
	public class UnfinishedDetail4TransMechanism{
		private int year;
		private int voltage;
		private String transMechanism;
		private List<MaintenanceStation> finishedBlanks=new ArrayList<>();//已完成的间隔
		private List<MaintenanceStation> unReachedPlanBlanks=new ArrayList<>();//未到计划日期的间隔
		private List<MaintenanceStation> overPlanBlanks=new ArrayList<>();//已超计划日期的间隔
		private List<MaintenanceStation> unfinishedBlanks=new ArrayList<>();//未完成的间隔
		private float finishRate=0;

		public String getTransMechanism() {
			return transMechanism;
		}
		public void setTransMechanism(String transMechanism) {
			this.transMechanism = transMechanism;
		}

		public float getFinishRate() {
			return finishRate;
		}
		public void setFinishRate(float finishRate) {
			this.finishRate = finishRate;
		}
		public int getVoltage() {
			return voltage;
		}
		public void setVoltage(int voltage) {
			this.voltage = voltage;
		}
		public int getYear() {
			return year;
		}
		public void setYear(int year) {
			this.year = year;
		}
		public List<MaintenanceStation> getFinishedBlanks() {
			return finishedBlanks;
		}
		public void setFinishedBlanks(List<MaintenanceStation> finishedBlanks) {
			this.finishedBlanks = finishedBlanks;
		}
		public List<MaintenanceStation> getUnReachedPlanBlanks() {
			return unReachedPlanBlanks;
		}
		public void setUnReachedPlanBlanks(List<MaintenanceStation> unReachedPlanBlanks) {
			this.unReachedPlanBlanks = unReachedPlanBlanks;
		}
		public List<MaintenanceStation> getOverPlanBlanks() {
			return overPlanBlanks;
		}
		public void setOverPlanBlanks(List<MaintenanceStation> overPlanBlanks) {
			this.overPlanBlanks = overPlanBlanks;
		}
		public List<MaintenanceStation> getUnfinishedBlanks() {
			return unfinishedBlanks;
		}
		public void setUnfinishedBlanks(List<MaintenanceStation> unfinishedBlanks) {
			this.unfinishedBlanks = unfinishedBlanks;
		}
	}


	/**
	 * 某调管范围内的特维信息
	 *
	 */
	public class MaintenanceBlanksInfo{
		private MaintenanceStation blank;
		private List<MaintenanceStationBreaker> breakers=new ArrayList<>();

		public MaintenanceBlanksInfo(MaintenanceStation blank,List<MaintenanceStationBreaker> breakers) {
			this.blank=blank;
			this.breakers=breakers;
		}

		public MaintenanceStation getBlank() {
			return blank;
		}
		public void setBlank(MaintenanceStation blank) {
			this.blank = blank;
		}
		public List<MaintenanceStationBreaker> getBreakers() {
			return breakers;
		}
		public void setBreakers(List<MaintenanceStationBreaker> breakers) {
			this.breakers = breakers;
		}

	}




	public MaintenanceStation getQueryMS() {
		return queryMS;
	}

	public void setQueryMS(MaintenanceStation queryMS) {
		this.queryMS = queryMS;
	}

	public String getCutPowerPlanQuery() {
		return cutPowerPlanQuery;
	}

	public void setCutPowerPlanQuery(String cutPowerPlanQuery) {
		this.cutPowerPlanQuery = cutPowerPlanQuery;
	}

	public String getFinishBeforeQuery() {
		return finishBeforeQuery;
	}

	public void setFinishBeforeQuery(String finishBeforeQuery) {
		this.finishBeforeQuery = finishBeforeQuery;
	}

	public String getFinishQuery() {
		return finishQuery;
	}

	public void setFinishQuery(String finishQuery) {
		this.finishQuery = finishQuery;
	}

	public Date getFinishedTimeStart() {
		return finishedTimeStart;
	}

	public void setFinishedTimeStart(Date finishedTimeStart) {
		this.finishedTimeStart = finishedTimeStart;
	}

	public Date getFinishedTimeEnd() {
		return finishedTimeEnd;
	}

	public void setFinishedTimeEnd(Date finishedTimeEnd) {
		this.finishedTimeEnd = finishedTimeEnd;
	}

	public UnfinishedDetail4TransMechanism getSelectedItem() {
		return selectedItem;
	}

	public void setSelectedItem(UnfinishedDetail4TransMechanism selectedItem) {
		this.selectedItem = selectedItem;
	}

	public Date getCurrentDate() {
		return currentDate;
	}

	public void setCurrentDate(Date currentDate) {
		this.currentDate = currentDate;
	}

	public List<MaintenanceBlanksInfo> getBlankInfos() {
		return blankInfos;
	}

	public void setBlankInfos(List<MaintenanceBlanksInfo> blankInfos) {
		this.blankInfos = blankInfos;
	}

	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}

	public List<SpFinishedDetail4Vol> getFinishedList4Vol() {
		return finishedList4Vol;
	}

	public void setFinishedList4Vol(List<SpFinishedDetail4Vol> finishedList4Vol) {
		this.finishedList4Vol = finishedList4Vol;
	}



}
